package freecomm.study.notes;

import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class EditNote extends Activity
{
    class MySpan extends ClickableSpan implements OnLongClickListener
    {
        Context mContext;
        MyContextMenu mContextMenu;

        @Override
        public void onClick(View widget)
        {
            // TODO Auto-generated method stub

        }

        public boolean onLongClick(View v)
        {
            // TODO Auto-generated method stub
            Log.i("shit", "shit");
            return false;
        }

    }

    class openDB extends AsyncTask<Void, Void, Cursor>
    {

        @Override
        protected Cursor doInBackground(Void... params)
        {
            // TODO Auto-generated method stub
            mNDH = new NoteDatabaseHelper(getApplicationContext());
            if (getIntent.getExtras() != null)
            {
                if (!isWidget)
                {
                    int mId = getIntent.getExtras().getInt("id");
                    Cursor mCursor = mNDH.query(mId);

                    return mCursor;
                } else
                {
                    Cursor mCursor = mNDH.queryByWidgetId(widgetId);
                    if (mCursor.getCount() == 0)
                    {
                        return null;
                    } else
                    {
                        return mCursor;
                    }
                }

            }
            return null;
        }

        @Override
        protected void onPostExecute(Cursor result)
        {
            // TODO Auto-generated method stub
            if (result != null)
            {
                result.moveToLast();
                String mText = result.getString(1);
                int mColor = result.getInt(2);
                switch (mColor)
                {
                case NotesActivity.BG_COLOR_ID_YELLOW:
                    setButtonColor(yellowButton.getId());

                    initEditText(yellowEditText, mText);
                    break;
                case NotesActivity.BG_COLOR_ID_RED:
                    setButtonColor(redButton.getId());
                    initEditText(redEditText, mText);

                    break;
                case NotesActivity.BG_COLOR_ID_PINK:
                    setButtonColor(pinkButton.getId());
                    initEditText(pinkEditText, mText);
                    break;
                case NotesActivity.BG_COLOR_ID_BLUE:
                    setButtonColor(blueButton.getId());
                    initEditText(blueEditText, mText);
                    break;
                case NotesActivity.BG_COLOR_ID_GREEN:
                    setButtonColor(greenButton.getId());
                    initEditText(greenEditText, mText);
                    break;
                }
            } else
            {
                yellowEditText.setVisibility(View.VISIBLE);
            }
            readingDatabaseTextView.setVisibility(View.GONE);
            contentLayout.setVisibility(View.VISIBLE);
            isChanged = false;
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            readingDatabaseTextView.setVisibility(View.VISIBLE);
            contentLayout.setVisibility(View.GONE);
            super.onPreExecute();
        }

    }

    class SaveNote extends AsyncTask<Void, Void, Boolean>
    {

        @Override
        protected Boolean doInBackground(Void... params)
        {
            // TODO Auto-generated method stub

            if (getIntent.getExtras() != null)
            {
                if (!getCurrentText().isEmpty())
                {
                    if (isWidget)
                    {
                        if (mNDH.queryByWidgetId(widgetId).getCount() == 0)
                        {
                            mNDH.insert(getCurrentText(), color, widgetId);
                        } else
                        {
                            mNDH.updateByWidgetId(getCurrentText(), color,
                                    clockBar.getText().toString(), widgetId);
                        }
                    } else
                    {
                        mNDH.update(getIntent.getExtras().getInt("id"),
                                getCurrentText(), color, clockBar.getText()
                                        .toString());
                    }
                } else
                {
                    if (isWidget)
                    {
                        if (mNDH.queryByWidgetId(widgetId).getCount() == 0)
                        {
                            return false;
                        } else
                        {
                            mNDH.deleteByWidget(widgetId);
                        }

                    }
                    mNDH.delete(getIntent.getExtras().getInt("id"));
                }
            } else
            {
                if (getCurrentText().isEmpty())
                {
                    return false;
                }
                mNDH.insert(getCurrentText(), color);

            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result)
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result)
            {
                Toast.makeText(EditNote.this, "保存完毕", Toast.LENGTH_SHORT)
                        .show();
            } else
            {
                Toast.makeText(EditNote.this, "没有内容可以保存", Toast.LENGTH_SHORT)
                        .show();
            }
            if (!isWidget)
            {
                startActivity(sendIntent);
            } else
            {
                RemoteViews views = new RemoteViews(
                        EditNote.this.getPackageName(), R.layout.note_widget);
                views.setViewVisibility(R.id.yellowBG, View.GONE);
                views.setViewVisibility(R.id.pinkBG, View.GONE);
                views.setViewVisibility(R.id.redBG, View.GONE);
                views.setViewVisibility(R.id.blueBG, View.GONE);
                views.setViewVisibility(R.id.greenBG, View.GONE);
                if (mNDH.queryByWidgetId(widgetId).getCount() == 0)
                {
                    views.setTextViewText(R.id.noteWidgetButton,
                            "点击此处添加标签");
                    views.setViewVisibility(R.id.yellowBG, View.VISIBLE);
                } else
                {
                    views.setTextViewText(R.id.noteWidgetButton,
                            getCurrentText());
                    switch (color)
                    {
                    case COLOR_ID_YELLOW:
                        views.setViewVisibility(R.id.yellowBG, View.VISIBLE);
                        break;
                    case COLOR_ID_PINK:
                        views.setViewVisibility(R.id.pinkBG, View.VISIBLE);
                        break;
                    case COLOR_ID_RED:
                        views.setViewVisibility(R.id.redBG, View.VISIBLE);
                        break;
                    case COLOR_ID_BLUE:
                        views.setViewVisibility(R.id.blueBG, View.VISIBLE);
                        break;
                    case COLOR_ID_GREEN:
                        views.setViewVisibility(R.id.greenBG, View.VISIBLE);
                        break;
                    default:
                        break;
                    }
                }
                Intent resultValue = new Intent(EditNote.this, EditNote.class);
                resultValue.setAction("freecomm.study.notes.EditNote"
                        + widgetId);
                resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        widgetId);
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        EditNote.this, 0, resultValue, 0);
                setResult(RESULT_OK, resultValue);
                views.setOnClickPendingIntent(R.id.noteWidgetButton,
                        pendingIntent);
                AppWidgetManager.getInstance(EditNote.this).updateAppWidget(
                        widgetId, views);

            }
            mNDH.close();
            finish();

        }

        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            Toast.makeText(EditNote.this, "正在保存...", Toast.LENGTH_SHORT).show();
            super.onPreExecute();
        }

    }

    private int widgetId;
    private boolean isWidget = false;
    private static final int COLOR_ID_BLUE = 3;
    private static final int COLOR_ID_GREEN = 4;
    private static final int COLOR_ID_PINK = 2;
    private static final int COLOR_ID_RED = 1;
    private static final int COLOR_ID_YELLOW = 0;
    private static boolean isChanged = false;
    private Button blueButton;
    private MyEditText blueEditText;
    private MyDigitalClock clockBar;
    private int color = 0;
    private OnClickListener colorButtonClickListener = new OnClickListener()
    {

        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            setButtonColor(v.getId());
        }
    };
    private LinearLayout contentLayout;
    private OnMenuItemClickListener contextMenuItemClickListener = new OnMenuItemClickListener()
    {

        @Override
        public boolean onMenuItemClick(MenuItem item)
        {
            // TODO Auto-generated method stub

            MyEditText mMyEditText = getCurrentEditText();
            String mUri = mMyEditText
                    .getText()
                    .toString()
                    .substring(mMyEditText.getSelectionStart(),
                            mMyEditText.getSelectionEnd());
            switch (item.getItemId())
            {

            case MyEditText.ADD_PHONE_TO_CONTACT:
                Intent addPhone = new Intent(Intent.ACTION_INSERT);
                addPhone.setType("vnd.android.cursor.dir/person");
                addPhone.setType("vnd.android.cursor.dir/contact");
                addPhone.setType("vnd.android.cursor.dir/raw_contact");
                addPhone.putExtra("phone", mUri);
                startActivity(addPhone);
                break;
            case MyEditText.SEND_SMS_TO_PHONE:

                Uri smsToUri = Uri.parse("smsto:" + mUri);
                Intent sendSMS = new Intent(
                        android.content.Intent.ACTION_SENDTO, smsToUri);
                startActivity(sendSMS);
                break;
            case MyEditText.COPY_URL:
                ClipboardManager clip = (ClipboardManager) EditNote.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                clip.setText(mUri);
                mMyEditText.setSelected(false);
                break;
            case MyEditText.ADD_EMAIL_TO_CONTACT:
                Intent addEmail = new Intent(Intent.ACTION_INSERT);
                addEmail.setType("vnd.android.cursor.dir/person");
                addEmail.setType("vnd.android.cursor.dir/contact");
                addEmail.setType("vnd.android.cursor.dir/raw_contact");
                addEmail.putExtra("email", mUri);
                startActivity(addEmail);
                break;
            case MyEditText.SEND_EMAIL_TO_ADDRESS:
                Intent sendEmail = new Intent(
                        android.content.Intent.ACTION_SEND);
                sendEmail.setType("text/plain");
                sendEmail.putExtra(android.content.Intent.EXTRA_EMAIL,
                        (new String[] { mUri }));

                startActivity(Intent.createChooser(sendEmail, mUri));
                break;
            case MyEditText.CALL_PHONE_NUMBER:
                Intent callPhone = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+mUri));
                startActivity(callPhone);
            default:
                break;
            }
            return false;
        }
    };
    private Intent getIntent;
    private Button greenButton;
    private MyEditText greenEditText;
    private NoteDatabaseHelper mNDH;
    private Button pinkButton;
    private MyEditText pinkEditText;
    private TextView readingDatabaseTextView;
    private Button redButton;
    private MyEditText redEditText;
    private Intent sendIntent;
    private TextWatcher textChange = new TextWatcher()
    {

        @Override
        public void afterTextChanged(Editable s)
        {
            // TODO Auto-generated method stub
            isChanged = true;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count)
        {
            // TODO Auto-generated method stub

        }
    };

    private Button yellowButton;

    private MyEditText yellowEditText;

    private MyEditText getCurrentEditText()
    {
        switch (color)
        {
        case COLOR_ID_YELLOW:
            return yellowEditText;

        case COLOR_ID_RED:
            return redEditText;

        case COLOR_ID_PINK:
            return pinkEditText;

        case COLOR_ID_BLUE:
            return blueEditText;

        case COLOR_ID_GREEN:
            return greenEditText;

        }
        return null;
    }

    private String getCurrentText()
    {
        String mTextString = "";
        switch (color)
        {
        case COLOR_ID_YELLOW:
            mTextString = yellowEditText.getText().toString();
            break;
        case COLOR_ID_RED:
            mTextString = redEditText.getText().toString();
            break;
        case COLOR_ID_PINK:
            mTextString = pinkEditText.getText().toString();
            break;
        case COLOR_ID_BLUE:
            mTextString = blueEditText.getText().toString();
            break;
        case COLOR_ID_GREEN:
            mTextString = greenEditText.getText().toString();
            break;

        default:
            break;
        }
        return mTextString;
    }

    public void initEditText(EditText mET, String content)
    {
        mET.setText(content);
        mET.setVisibility(View.VISIBLE);
        mET.setSelection(content.length());
        mET.requestFocus();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.edit_note);
        setResult(RESULT_CANCELED);
        sendIntent = new Intent(EditNote.this, NotesActivity.class);
        getIntent = getIntent();
        yellowEditText = (MyEditText) findViewById(R.id.yellowEditText);
        redEditText = (MyEditText) findViewById(R.id.redEditText);
        pinkEditText = (MyEditText) findViewById(R.id.pinkEditText);
        blueEditText = (MyEditText) findViewById(R.id.blueEditText);
        greenEditText = (MyEditText) findViewById(R.id.greenEditText);
        yellowButton = (Button) findViewById(R.id.yellowButton);
        redButton = (Button) findViewById(R.id.redButton);
        pinkButton = (Button) findViewById(R.id.pinkButton);
        blueButton = (Button) findViewById(R.id.blueButton);
        greenButton = (Button) findViewById(R.id.greenButton);
        yellowButton.setOnClickListener(colorButtonClickListener);
        redButton.setOnClickListener(colorButtonClickListener);
        pinkButton.setOnClickListener(colorButtonClickListener);
        blueButton.setOnClickListener(colorButtonClickListener);
        greenButton.setOnClickListener(colorButtonClickListener);
        clockBar = (MyDigitalClock) findViewById(R.id.clockBar);
        contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
        readingDatabaseTextView = (TextView) findViewById(R.id.readingDatabaseTextView);
        yellowEditText.setOnMenuItemClickListener(contextMenuItemClickListener);
        yellowEditText.addTextChangedListener(textChange);
        redEditText.setOnMenuItemClickListener(contextMenuItemClickListener);
        redEditText.addTextChangedListener(textChange);
        pinkEditText.setOnMenuItemClickListener(contextMenuItemClickListener);
        pinkEditText.addTextChangedListener(textChange);
        blueEditText.setOnMenuItemClickListener(contextMenuItemClickListener);
        blueEditText.addTextChangedListener(textChange);
        greenEditText.setOnMenuItemClickListener(contextMenuItemClickListener);
        greenEditText.addTextChangedListener(textChange);
        if (getIntent.getExtras() != null
                && (widgetId = getIntent.getExtras().getInt(
                        AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID)) != AppWidgetManager.INVALID_APPWIDGET_ID)
        {
            isWidget = true;
        }
        new openDB().execute();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if (isChanged)
            {
                new SaveNote().execute();
            } else
            {
                if (!isWidget)
                {
                    startActivity(sendIntent);
                } else
                {

                    RemoteViews views = new RemoteViews(
                            EditNote.this.getPackageName(), R.layout.note_widget);
                    if (mNDH.queryByWidgetId(widgetId).getCount() == 0)
                    {
                        views.setTextViewText(R.id.noteWidgetButton,
                                "点击此处添加标签");
                        views.setViewVisibility(R.id.yellowBG, View.VISIBLE);
                    }Intent resultValue = new Intent(EditNote.this, EditNote.class);
                    resultValue.setAction("freecomm.study.notes.EditNote"
                            + widgetId);
                    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                            widgetId);
                    PendingIntent pendingIntent = PendingIntent.getActivity(
                            EditNote.this, 0, resultValue, 0);
                    setResult(RESULT_OK, resultValue);
                    views.setOnClickPendingIntent(R.id.noteWidgetButton,
                            pendingIntent);
                    AppWidgetManager.getInstance(EditNote.this).updateAppWidget(
                            widgetId, views);
                    
                }
                mNDH.close();
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void openContextMenu(String[] mStrings,
            OnItemClickListener mListener)
    {
        MyContextMenu mCM = new MyContextMenu(this, mStrings, mListener);
        mCM.showAtLocation(null, Gravity.CENTER, 0, 0);
    }

    private void setButtonColor(int mID)
    {
        yellowButton.setBackgroundResource(R.drawable.color_1);
        redButton.setBackgroundResource(R.drawable.color_2);
        pinkButton.setBackgroundResource(R.drawable.color_3);
        blueButton.setBackgroundResource(R.drawable.color_4);
        greenButton.setBackgroundResource(R.drawable.color_5);

        setEditTextGone();
        switch (mID)
        {
        case R.id.yellowButton:
            // noteEditText.setBackgroundResource(R.drawable.notes_bg_yellow_01);

            setEditText(yellowEditText);
            clockBar.setBackgroundResource(R.drawable.notes_bg_yellow_02);
            yellowButton.setBackgroundResource(R.drawable.color_1_focus);
            color = COLOR_ID_YELLOW;
            break;
        case R.id.redButton:
            // noteEditText.setBackgroundResource(R.drawable.notes_bg_red_01);
            setEditText(redEditText);
            clockBar.setBackgroundResource(R.drawable.notes_bg_red_02);
            redButton.setBackgroundResource(R.drawable.color_2_focus);
            color = 1;
            break;
        case R.id.pinkButton:
            // noteEditText.setBackgroundResource(R.drawable.notes_bg_pink_01);
            setEditText(pinkEditText);
            clockBar.setBackgroundResource(R.drawable.notes_bg_pink_02);
            pinkButton.setBackgroundResource(R.drawable.color_3_focus);
            color = 2;
            break;
        case R.id.blueButton:
            // noteEditText.setBackgroundResource(R.drawable.notes_bg_blue_01);
            setEditText(blueEditText);
            clockBar.setBackgroundResource(R.drawable.notes_bg_blue_02);
            blueButton.setBackgroundResource(R.drawable.color_4_focus);
            color = COLOR_ID_BLUE;
            break;
        case R.id.greenButton:
            // noteEditText.setBackgroundResource(R.drawable.notes_bg_green_01);
            setEditText(greenEditText);
            clockBar.setBackgroundResource(R.drawable.notes_bg_green_02);
            greenButton.setBackgroundResource(R.drawable.color_5_focus);
            color = COLOR_ID_GREEN;
            break;
        default:
            break;
        }
    }

    private void setEditText(EditText mET)
    {
        mET.setText(getCurrentText());
        mET.setVisibility(View.VISIBLE);
        mET.setSelection(mET.getText().toString().length());
        mET.requestFocus();
    }

    private void setEditTextGone()
    {
        switch (color)
        {
        case COLOR_ID_YELLOW:
            yellowEditText.setVisibility(View.GONE);
            break;
        case COLOR_ID_RED:
            redEditText.setVisibility(View.GONE);
            break;
        case COLOR_ID_PINK:
            pinkEditText.setVisibility(View.GONE);
            break;
        case COLOR_ID_BLUE:
            blueEditText.setVisibility(View.GONE);
            break;
        case COLOR_ID_GREEN:
            greenEditText.setVisibility(View.GONE);
            break;

        default:
            break;
        }
    }
}
